<template>
        <div class="layui-form layui-form-pane layui-tab-item layui-show">
            <div class="layui-form-item">
              <div class="avatar-add">
                <p>建议尺寸168*168，支持jpg、png、gif，最大不能超过50KB</p>
                <label   for="pic" class="layui-btn upload-img">
                  <i class="layui-icon">&#xe67c;</i>上传头像
                  <input id="pic" type="file" name="file" accept="image/*" @change="upload">
                </label>
                <img :src="pic">
                <span class="loading"></span>
              </div>
            </div>
          </div>
</template>

<script>
  import { uploadImg } from '@/api/content'
  import { updateUserInfo } from '@/api/user'
  import config from '@/config'
export default {
    name: 'picupload',
    components: {

    },
    props: {

    },
    data() {
        return {
          pic: (this.$store.state.userInfo &&
          this.$store.state.userInfo.pic ) ? this.$store.state.userInfo.pic :'http://localhost:3000/images/avatar/2.jpg',
          formData: ''
        };
    },
    computed: {

    },
    created() {

    },
    mounted() {

    },
    watch: {

    },
    methods: {
      upload(e){
        const file = e.target.files
        const formData = new FormData()
        if(file.length > 0 ){
          formData.append('file', file[0])
          this.formData = formData
        }
        //上传图片
        uploadImg(this.formData).then((res)=>{
          // console.log(res.data);
          if(res.code === 200){
            const baseUrl = 
             process.env.NODE_ENV === 'production' ? config.baseUrl.pro : config.baseUrl.dev
            this.pic = baseUrl  + res.data
               //更新用户资料
          updateUserInfo({pic: this.pic}).then((res)=>{
            if(res.code === 200){
              //修改全局用户信息
              let user = this.$store.state.userInfo
              user.pic = this.pic
              this.$store.commit('setUserInfo',user)
              this.$alert('头像更改成功')
            }
          })
          document.getElementById('pic').value = ''
          }
        })
        
      }
    },
};
</script>

<style scoped lang="scss">
#pic{
  display: none;
}
</style>
